import React, { useEffect } from "react";
import { Form, Input, Button, Toast } from "antd-mobile";
import axios from "axios";
import { useNavigate, useSearchParams } from "react-router-dom";
import { useDispatch } from "react-redux";
import { loginSuccess } from "../../store/user/userSlice";
const Login = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [searchParams] = useSearchParams()
  const from = searchParams.get("from") || "/";
  const onFinish = async (values) => {
    const resp = await axios.post("/api/login", values);
    const { code, message, data } = resp.data;
    if (code === 200) {
      dispatch(loginSuccess(data));
      localStorage.setItem("token", data.token);
      Toast.show(message);
      navigate(from, { replace: true });
    } else {
      Toast.show(message);
    }
  };
  return (
    <div>
      <Form
        onFinish={onFinish}
        layout="horizontal"
        footer={
          <Button type="submit" block color="primary">
            登录
          </Button>
        }
      >
        <Form.Item rules={[{ required: true },{pattern:/^(?:(?:\+|00)86)?1[3-9]\d{9}$/}]} label="用户名" name="username">
          <Input placeholder="请输入用户名"></Input>
        </Form.Item>
        <Form.Item rules={[{ required: true },{pattern:/^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]/}]} label="密码" name="password">
          <Input placeholder="请输入密码"></Input>
        </Form.Item>
      </Form>
    </div>
  );
};
export default Login;
